<script setup lang="ts">
/*
 watch:侦听器
    某些值的change事件
    const stop=watch('需要侦听的数据/[]/()=>对象.属性',(newVal,oldVal)=>{},{
      deep:深度侦听
      immediate:是否初次定义就执行回调
      flush:
          pre:默认渲染前调用回调
          post:渲染后执行回调
          sync:修改一次执行一次回调
    })
*/
import { ref, watch } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs' // 如果报错  @types/dayjs
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import type { articlesApi, resultsItem } from '../types/channels'
import { useChannel } from '../store/channel'
const store = useChannel()
// const props = defineProps<{
//   channelId: number
// }>()
const list = ref<resultsItem[]>([])
watch(
  () => store.channelId,
  async newVal => {
    // 调用接口获取列表数据存储并渲染
    console.log(newVal)
    const res = await axios<articlesApi>({
      url: `http://geek.itheima.net/v1_0/articles?channel_id=${newVal}&timestamp=${Date.now()}`
    })
    list.value = res.data.data.results
    console.log(res)
  }
)

// 过滤器：字符转换，
dayjs.extend(relativeTime)
dayjs.locale('zh-cn') // 中文
function formatTime(str: string) {
  return dayjs(str).fromNow() // 22 年前
}
</script>

<template>
  <div class="article-list">
    <div class="article-item" v-for="i in list" :key="i.art_id">
      <p class="title">
        {{ i.title }}
      </p>
      <img
        v-for="(item, index) in i.cover.images"
        :key="index"
        class="img"
        :src="item"
        alt=""
      />

      <div class="info">
        <span>{{ i.aut_name }}</span>
        <span>{{ i.comm_count }}评论</span>
        <span>{{ formatTime(i.pubdate) }}</span>
      </div>
    </div>
  </div>
</template>
